<?php
/**
 * articles model
 *
 *
 * @author:		qfox
 * @package:	radiance
 * @copyright:	(c) 2011, alex <qfox@ya.ru> yaroshevich aka alex_ez. All rights reserved
 * @created:	11.05.2011, 14:34
 */

class articles extends model {

	protected $table = 'core_articles';
	protected $linked_table = 'core_articles_links';
	protected $linked_field = 'article_id';

	protected $states = array('raw', 'active', 'hidden', 'deleted');
	protected $type = array('article', 'action');

	public function get_above( $id ) {
		$prev = 'SELECT * FROM `%1$s` WHERE `date` <= (SELECT `date` FROM `%1$s` WHERE id=%2$d) AND id<%2$d ORDER BY `date` DESC, id DESC LIMIT 1;';
		$next = 'SELECT * FROM `%1$s` WHERE `date` >= (SELECT `date` FROM `%1$s` WHERE id=%2$d) AND id>%2$d ORDER BY `date` ASC, id ASC LIMIT 1;';

		$r = array( );
		foreach( array( 'prev', 'next' ) as $k ) {
			$sql = sprintf( $$k, $this ->table, $id );
			$r[$k] = $this ->db ->_row( $sql, 'id' );
		}
		return $r;
	}

	public function get_states() {
		return array(
			'raw'		=> __('Raw'),
			'active' 	=> __('Active'),
			'hidden'	=> __('Hidden'),
			'deleted'	=> __('Deleted'),
			);
	}

	public function get_types() {
		return array(
			'article' => __('Article'),
			'action' => __('Action'),
			);
	}

	public function get_types_texts() {

		return array(
			'article' => array(
				'acc' => 'публикацию %1$s',
				'nom' => 'Публикация %1$s',
				'nomp' => 'Публикации %1$s',
				),

			'action' => array(
				'acc' => 'акцию',
				'nom' => 'Акция',
				'nomp' => '%2$s',
				),
			);
	}

	public function by_weights( $ids )
	{
		$count = 5;
		//$r = $this ->getBy( array( 'id' => array_keys( $ids ) ),
		//	'ifnull(elt(field(`id`,'..' ), '.join(',',array_values($ids)).' ),0) ASC',
		//	array( 0, 4 ) );
		if( !$ids ) return array( );
		
		$sql = sprintf(
			'SELECT * FROM %1$s WHERE id IN (%2$s) ORDER BY ifnull(elt(field(`id`,%2$s),%3$s),1000) ASC LIMIT 0,%4$d;',
			$this ->table, join(',',array_keys($ids)), join(',',array_values($ids)), $count );
		
		bc::log( $sql, 'sql' );
		$r = $this ->db ->_list( $sql, 'id' );
		return $r;
	}

	function counts( $types = '' )
	{
		$types = explode( ',', $types );
		$sql = 'SELECT DISTINCT group_id, item_type, item_id FROM %2$s AS l INNER JOIN %1$s AS a on a.id = l.%3$s WHERE %4$s AND l.state="on";';
		$sql = sprintf( $sql, $this ->table, $this ->linked_table, $this ->linked_field, $this ->db ->make_set_list( array( 'item_type' => $types ), 'AND' ) );
		
		$r = $this ->db ->_list( $sql );
		//bc::log( array( 'sql' => $sql, 'result' => $r ), 'getCounts' );
		
		return $r;
	}
}

